import React, { Component } from 'react';
import _ from 'underscore';
import cx from 'classnames';
import numeral from 'numeral';

export default class Multi extends Component {
  constructor(props, context){
    super(props, context);
    this.state = {
      cols: this.resetColumns(props),
      dateSortOrientation: -1,
      currentSort: null,
      currentSortOrientation: -1
    }; // state
  } // constructor

  componentWillReceiveProps(nextProps) {
    this.setState({
      cols: this.resetColumns(nextProps)
    });
  } // componentWillReceiveProps

  resetColumns(props) {
    return _.map(props.cols, col => _.defaults(col, {
      title: '',
      className: '',
      sortable: false
    }));
  } // resetColumns

  sortHandler(column, index) {
      column.sort.call(this, column, index);
  } // sortHandler

  existSubpage(column) {
    let identity = '.unique'
      , index = column.key.indexOf(identity);

    return (identity.length + index) === column.key.length;
  } // existSubpage

  subpageHandler(item) {
    if (this.props.onClick) {
      this.props.onClick(condition => {
        let event = item[1].key.split('.')[1];
        condition.measures = _.filter(condition.measures, p => p.event_name === event && p.aggregator === 'unique');
        condition.slice_date = item[0].date;
        condition.slice_by_values = item[0].by_values;
        return condition;
      });
    }
  } // subpageHandler

  renderTableHeaderCell(column, index, widthPercent) {
    return (
      <th
        key={ `${ column.key }-${ index }` }
        className="sortedth"
        style={{ width: widthPercent }}
        onClick={ this.sortHandler.bind(this, column, index) }>
        <span className="sortedtext">
          { column.title }
        </span>
        <span className={ cx(column.className, 'sorted-arrow', {
          'desc': this.state.currentSort === column.key && this.state.currentSortOrientation === -1,
          'asc': this.state.currentSort === column.key && this.state.currentSortOrientation === 1
        }) } />
      </th>
    );
  } // renderTableHeaderCell

  renderTableHeader() {
    let defaultColumn = this.state.cols[0];
    let widthPercent = numeral(1 / (this.state.cols.length - 1)).format('0.00%');
    return (
      <thead>
        <tr>
          <th
            key="date"
            className="sortedth col-date"
            onClick={ this.sortHandler.bind(this, defaultColumn, 0) }>
            <span className="sortedtext">
              { defaultColumn.title }
            </span>
            <span className={ cx(defaultColumn.className, 'sorted-arrow', {
              'desc': this.state.dateSortOrientation === -1,
              'asc': this.state.dateSortOrientation === 1
            }) } />
          </th>
          <th>
            <table style={{ width: '100%' }}>
              <thead>
                <tr>
                  {
                    _.chain(this.state.cols)
                      .filter((p, i) => i !== 0)
                      .map((p, i) => this.renderTableHeaderCell(p, i, widthPercent), this)
                      .value()
                  }
                </tr>
              </thead>
            </table>
          </th>
        </tr>
      </thead>
    );
  } // renderTableHeader

  renderTableBody(data) {
    let rowGenerator = rowValue => {
      let widthPercent = numeral(1 / rowValue.length).format('0.00%');
      return _.map(rowValue, (item, i) => {
        if (typeof item[0] === 'string') {
          return (
            <td key={ item[1].key } style={{ width: widthPercent }}>
              { item[0] }
            </td>
          );
        } else {
          let content = (<div>{ item[0].value === null ? '--' : item[0].value }</div>);
          if (this.existSubpage(item[1]) && item[0].value && item[0].value !== '--') {
            content = (
              <a
                data-tip="查看详细用户列表"
                onClick={ this.subpageHandler.bind(this, item) }
                style={{
                  display: 'inline-block',
                  cursor: 'pointer'
                }}>
                { item[0].value }
              </a>
            );
          }
          return (
            <td key={ item[1].key } style={{ width: widthPercent }}>
              {
                item[0].value !== undefined ? content : null
              }
              <div className={ cx('ratio', {
                'ratio-neg': item[0].percentValue < 0,
                'ratio-pos': item[0].percentValue >= 0
              }) }>{ item[0].percent }</div>
            </td>
          );
        }
      });
    };

    let sortSumByDetail = sum => {
      if (sum && sum.length && data.length && data[0].value && data[0].value.length) {
        let dataNames = _.map(data[0].value, p => p[1]);
        let list = [];
        for (var i = 0; i < dataNames.length; i++) {
          let item = _.find(sum[0].value, p => p[1] === dataNames[i]);
          if (item) {
            list.push(item);
          }
        }
        sum[0].value = list;
      }
    };

    let { sum } = this.props;
    if (this.state.currentSort) {
      if (sum && sum.length && data.length && data[0].value && data[0].value.length) {
        let colIndex = _.findIndex(this.state.cols, p => p.key === this.state.currentSort);
        if (colIndex === 1) {
          sum[0].value = _.sortBy(sum[0].value, p => p[colIndex]);
          if (this.state.currentSortOrientation === -1) {
            sum[0].value = sum[0].value.reverse();
          }
        } else if (colIndex > 1) {
          sum[0].value = _.sortBy(sum[0].value, p => p[colIndex].value || p[colIndex].percent);
          if (this.state.currentSortOrientation === -1) {
            sum[0].value = sum[0].value.reverse();
          }
        } else {
          sortSumByDetail(sum);
        }
      }
    } else {
      sortSumByDetail(sum);
    }

    return (
      <tbody>
        {
          !(sum && sum.length && data.length && data[0].value && data[0].value.length) ? null : _.map(sum, row => {
            return (
              <tr key="total">
                <td key="date">合计</td>
                <td>
                  <table className="table table-striped">
                    <tbody>
                      {
                        _.map(row.value, (rowValue, i) => (
                          <tr key={ i }>
                            { rowGenerator(_.filter(_.zip(rowValue, this.state.cols), (p, i) => i !== 0)) }
                          </tr>
                        ))
                      }
                    </tbody>
                  </table>
                </td>
              </tr>
            )
          })
        }
        {
          _.map(data, row => {
            return (
              <tr key={ row.key }>
                <td key="date">
                  { row.key }
                </td>
                <td>
                  <table className="table table-striped">
                    <tbody>
                      {
                        _.map(row.value, (rowValue, i) => (
                          <tr key={ i }>
                            { rowGenerator(_.filter(_.zip(rowValue, this.state.cols), (p, i) => i !== 0)) }
                          </tr>
                        ))
                      }
                    </tbody>
                  </table>
                </td>
              </tr>
            )
          })
        }
      </tbody>
    );
  } // renderTableBody

  render() {
    let defaultColumn = this.state.cols[0];
    return (
      <div style={{
        whiteSpace: 'nowrap',
        overflowX: 'auto',
        overflowY: 'hidden'
      }}>
        <table className="table table-striped event-table">
          <colgroup>
            <col width="160" />
            <col width="*" />
          </colgroup>
          { this.renderTableHeader() }
          { this.renderTableBody(this.props.data) }
        </table>
      </div>
    );
  } // render
}

Multi.defaultProps = {
  cols: [],
  data: []
}
